import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:get/get.dart';
import 'package:like_button/like_button.dart';
import 'package:live_music/components/feedback/PageFeedBack.dart';
import 'package:live_music/components/index/momentCard.dart';
import 'package:live_music/components/ui/theme.dart';
import 'package:live_music/event/momonEvent.dart';
import 'package:live_music/models/comment_detail_model.dart';
import 'package:live_music/models/notification_detail_model.dart';
import 'package:live_music/models/user_info_model.dart';
import 'package:live_music/pages/friendList/widget/list_card_friend.dart';
import 'package:live_music/pages/home/message/message_page/atAndCommentInfo_card.dart';
import 'package:live_music/pages/home/message/message_page/follow_card.dart';
import 'package:live_music/pages/publish/widget/frinend_list_select_publish.dart';
import 'package:live_music/services/commentService.dart';
import 'package:live_music/services/notificationService.dart';
import 'package:live_music/services/operationServiece.dart';
import 'package:live_music/services/userService.dart';
import 'package:live_music/utils/cgq_utils.dart';
import 'package:live_music/utils/colors.dart';
import 'package:live_music/utils/commentParse.dart';
import 'package:live_music/utils/eventBusUtils.dart';
import 'package:live_music/utils/screen_utils.dart';
import 'package:live_music/utils/sp_utils.dart';
import 'package:live_music/utils/toast_utils.dart';
import 'package:live_music/utils/util.dart';

class CommentDetailPage extends StatefulWidget {
  CommentDetailPage({Key key, this.momentId, this.commentId}) : super(key: key);
  int momentId;
  int commentId;
  @override
  _CommentDetailPageState createState() => _CommentDetailPageState();
}

class _CommentDetailPageState extends State<CommentDetailPage>
    with AutomaticKeepAliveClientMixin, WidgetsBindingObserver {
  EasyRefreshController _easyRefreshController;
  // 独立的滚动视图 防止tab切换时触发下拉刷新
  ScrollController _scrollController;
  // 列表数组模型
  List<CommentDetailModel> _commentListModel;
  CommentDetailModel _commentDetail;
  int pageNo = 1;
  int pageSize = 20;
  bool hasMore = true;
  bool loading = true;
  bool error = false;
  String errorMsg;

  TextEditingController _commentEditController;
  CommentDetailModel parentComment;
  bool isShowkeyborad = false;
  bool disabledPublish = true;
  FocusNode _focusNode = FocusNode();
    List options = ['删除'];
  void initState() {
    super.initState();
    _easyRefreshController = EasyRefreshController();
    _commentEditController = TextEditingController();
    _scrollController = ScrollController();
    EventBusUtils.getInstance().on<SelectFriendPublishEvent>().listen((event) {
      setState(() {
        _commentEditController.text =
            _commentEditController.text + event.name + " ";
      });
    });
    WidgetsBinding.instance?.addObserver(this);
    getData();
    getDetailData();
  }

  @override
  void dispose() {
    _easyRefreshController.dispose();
    _scrollController.dispose();
    WidgetsBinding.instance?.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeMetrics() {
    super.didChangeMetrics();
    WidgetsBinding.instance?.addPostFrameCallback((_) {
      setState(() {
        if (MediaQuery.of(context).viewInsets.bottom == 0) {
          //关闭键盘
          isShowkeyborad = false;
        } else {
          //显示键盘
          isShowkeyborad = true;
        }
      });
    });
  }

  getDetailData({bool replace = true}) async {
    try {
      Map<String, dynamic> data = {
        "commentId": widget.commentId,
      };
      Map<String, dynamic> result = await CommentService.getCommentDetail(data);
      CommentDetailModel commentDetail =
          CommentDetailModel.fromJson(result['body']);
      setState(() {
        _commentDetail = commentDetail;
      });
    } catch (e) {
      ToastUtils.showToast(e['retdesc'] != null ? e['retdesc'] : '出现异常');
      Get.back();
    }
  }

  getData({bool replace = true}) async {
    try {
      Map<String, dynamic> data = {
        "pageNo": pageNo,
        "pageSize": pageSize,
        "momentId": widget.momentId,
        "parentId": widget.commentId,
      };
      Map<String, dynamic> result =
          await CommentService.queryMomentComment(data);
      CommentListModel commentListModel =
          CommentListModel.fromJson(result['body']);
      setState(() {
        pageNo++;
        hasMore = pageSize == commentListModel.list.length;
        if (replace) {
          _commentListModel = commentListModel.list;
        } else {
          _commentListModel.addAll(commentListModel.list);
        }
      });
    } catch (e) {
      setState(() {
        error = true;
        errorMsg = e.toString();
      });
    } finally {
      setState(() {
        loading = false;
      });
    }
  }

  // 刷新回调(null为不开启刷新)
  Future _onRefresh() async {
    setState(() {
      pageNo = 1;
    });
    await getData(replace: true);
    if (error) {
      setState(() => error = false);
    }
    // 恢复刷新状态 使onLoad再次可用
    _easyRefreshController.resetLoadState();
  }

  // 加载回调(null为不开启加载)
  Future _onLoad() async {
    if (hasMore) {
      await getData(replace: false);
    }
    // // 结束加载
    // _easyRefreshController.finishLoad(success: true, noMore: !hasMore);
    await Future.delayed(const Duration(seconds: 0), () {
      _easyRefreshController.finishLoad(success: true, noMore: !hasMore);
    });
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    double screeHeight = MediaQuery.of(context).size.height;
    return Scaffold(
        backgroundColor: ColorRes.themeBg,
        appBar: AppBar(
          backgroundColor: Colors.white,
          title: Text(
            '评论详情',
            style: TextStyle(color: Colors.black, fontSize: 16),
          ),
          centerTitle: true,
        ),
        body: Container(
            height: screeHeight,
            width: MediaQuery.of(context).size.width,
            child: Stack(children: [
              Container(
                  padding: EdgeInsets.symmetric(horizontal: 10, vertical: 20),
                  child: Column(children: [
                    Container(
                      decoration: BoxDecoration(
                          border: Border(
                        bottom: BorderSide(width: .5, color: WcaoTheme.outline),
                      )),
                      width: screenWidth(context),
                      margin: EdgeInsets.only(bottom: 15),
                      padding: EdgeInsets.only(bottom: 15),
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          SizedBox(
                            width: 30,
                            height: 30,
                            child: ClipRRect(
                              borderRadius: BorderRadius.circular(15),
                              child: CgqUtils.imageCache(
                                  _commentDetail.userAvatarUrl,
                                  fit: BoxFit.cover),
                            ),
                          ),
                          SizedBox(
                            width: 10,
                          ),
                          Expanded(
                              child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                _commentDetail.userName,
                                style: TextStyle(
                                    color: Colors.black,
                                    fontWeight: FontWeight.bold,
                                    fontSize: 14),
                              ),
                              SizedBox(
                                height: 3,
                              ),
                              Text(getDateTime(_commentDetail.createTime),
                                  style: TextStyle(
                                      color: Colors.grey[400], fontSize: 10)),
                              SizedBox(
                                height: 5,
                              ),
                              CommentParse(
                                _commentDetail.content,
                                style: TextStyle(
                                  fontSize: 12,
                                  color: Colors.black,
                                ),
                              ),
                              SizedBox(
                                height: 5,
                              ),
                            ],
                          )),
                          SizedBox(
                            width: 10,
                          ),
                          Column(
                            children: [
                              LikeButton(
                                  isLiked: _commentDetail.hasLiked,
                                  onTap: (isLiked) {
                                    return onTapLikeButton(!isLiked, -1);
                                  },
                                  size: 20,
                                  circleColor: CircleColor(
                                      start: ColorRes.color_3,
                                      end: ColorRes.color_3),
                                  likeBuilder: (isLike) {
                                    return isLike == true
                                        ? Image.asset(
                                            'assets/images/common/red_heart.webp')
                                        : Icon(
                                            Icons.favorite_border_outlined,
                                            size: 20,
                                            color: WcaoTheme.secondary,
                                          );
                                  },
                                  bubblesColor: const BubblesColor(
                                    dotPrimaryColor: ColorRes.color_3,
                                    dotSecondaryColor: ColorRes.color_3,
                                    dotThirdColor: ColorRes.color_3,
                                    dotLastColor: ColorRes.color_3,
                                  )),
                              Text(
                                _commentDetail.likeCount.toString(),
                                style:
                                    TextStyle(fontSize: 12, color: Colors.grey),
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                    Container(
                      alignment: Alignment.centerLeft,
                      margin: EdgeInsets.only(bottom: 15),
                      child: Text(
                        "全部评论",
                        style: TextStyle(
                            color: Colors.black,
                            fontWeight: FontWeight.bold,
                            fontSize: 14),
                      ),
                    ),
                    Container(
                        height: screeHeight - 265,
                        child: EasyRefresh(
                            firstRefresh: true,
                            firstRefreshWidget:
                                PageFeedBack(firstRefresh: true).build(),
                            emptyWidget: PageFeedBack(
                              loading: loading,
                              error: error,
                              empty: _commentListModel.isEmpty,
                              errorMsg: errorMsg,
                              onErrorTap: () =>
                                  _easyRefreshController.callRefresh(),
                              onEmptyTap: () =>
                                  _easyRefreshController.callRefresh(),
                            ).build(),
                            header: ClassicalHeader(),
                            footer: ClassicalFooter(),
                            controller: _easyRefreshController,
                            enableControlFinishRefresh: false,
                            enableControlFinishLoad: true,
                            onRefresh: _onRefresh,
                            onLoad: _commentListModel.isEmpty ? null : _onLoad,
                            child: ListView.builder(
                                controller: _scrollController,
                                itemCount: _commentListModel.length,
                                itemBuilder: (BuildContext context, int index) {
                                  CommentDetailModel e =
                                      _commentListModel[index];
                                  return InkWell(
                            onLongPress: () async {
                                  Map<String, dynamic> localuserLogin = await SPUtil.getObject('userLogin');
                              if (localuserLogin['userId'] == e.userId) {
                              return showModalBottomSheet<int>(
                                  isScrollControlled: false,
                                  context: context,
                                  shape: RoundedRectangleBorder(
                                    borderRadius: const BorderRadius.only(
                                      topLeft: Radius.circular(10),
                                      topRight: Radius.circular(10),
                                    ),
                                  ),
                                  builder: (BuildContext context) {
                                    return Container(
                                      constraints: BoxConstraints(
                                          minHeight: 60, maxHeight: 60),
                                      child: ListView.builder(
                                        itemBuilder:
                                            (BuildContext context, int index) {
                                          return ListTile(
                                              title: Text( options[index] ),
                                              onTap: () async {
                                                if (index == 0) {
                                                  await CommentService
                                                      .deleteComment({
                                                    "commentId": e.id
                                                  });
                                                  setState(() {
                                                    _commentListModel
                                                        .removeAt(index);
                                                  });
                                                }
                                                Navigator.of(context)
                                                    .pop(index);
                                              });
                                        },
                                        itemCount: options.length,
                                      ),
                                    );
                                  });
                              }
                            },
                            child: Container(
                                    decoration: BoxDecoration(
                                        border: Border(
                                      bottom: BorderSide(
                                          width: .5, color: WcaoTheme.outline),
                                    )),
                                    width: screenWidth(context),
                                    margin: EdgeInsets.only(bottom: 15),
                                    padding: EdgeInsets.only(bottom: 15),
                                    child: Row(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        SizedBox(
                                          width: 30,
                                          height: 30,
                                          child: ClipRRect(
                                            borderRadius:
                                                BorderRadius.circular(15),
                                            child: CgqUtils.imageCache(
                                                e.userAvatarUrl,
                                                fit: BoxFit.cover),
                                          ),
                                        ),
                                        SizedBox(
                                          width: 10,
                                        ),
                                        Expanded(
                                            child: Column(
                                          crossAxisAlignment:
                                              CrossAxisAlignment.start,
                                          children: [
                                            Text(
                                              e.userName,
                                              style: TextStyle(
                                                  color: Colors.black,
                                                  fontWeight: FontWeight.bold,
                                                  fontSize: 14),
                                            ),
                                            SizedBox(
                                              height: 3,
                                            ),
                                            Text(getDateTime(e.createTime),
                                                style: TextStyle(
                                                    color: Colors.grey[400],
                                                    fontSize: 10)),
                                            SizedBox(
                                              height: 5,
                                            ),
                                            InkWell(
                                                onTap: () {
                                                  if (parentComment == null) {
                                                    setState(() {
                                                      parentComment = e;
                                                    });
                                                    return;
                                                  }
                                                  if (e.id ==
                                                      parentComment.id) {
                                                    setState(() {
                                                      parentComment = null;
                                                    });
                                                  } else {
                                                    setState(() {
                                                      parentComment = e;
                                                    });
                                                  }
                                                },
                                                child: CommentParse(
                                                  e.content,
                                                  style: TextStyle(
                                                    fontSize: 12,
                                                    color: Colors.black,
                                                  ),
                                                )),
                                            SizedBox(
                                              height: 5,
                                            ),
                                            e.replyToComment != null
                                                ? Wrap(
                                                    children: [
                                                      Text(
                                                        "@" +
                                                            e.replyToComment
                                                                .userName,
                                                        style: TextStyle(
                                                          fontSize: 12,
                                                          color:
                                                              Colors.blueAccent,
                                                        ),
                                                      ),
                                                      SizedBox(
                                                        width: 2,
                                                      ),
                                                      Text(
                                                        e.replyToComment
                                                            .content,
                                                        style: TextStyle(
                                                          fontSize: 12,
                                                          color: Colors.black,
                                                        ),
                                                      )
                                                    ],
                                                  )
                                                : Container()
                                          ],
                                        )),
                                        SizedBox(
                                          width: 10,
                                        ),
                                        Column(
                                          children: [
                                            LikeButton(
                                                isLiked: e.hasLiked,
                                                onTap: (isLiked) {
                                                  return onTapLikeButton(
                                                      !isLiked, index);
                                                },
                                                size: 20,
                                                circleColor: CircleColor(
                                                    start: ColorRes.color_3,
                                                    end: ColorRes.color_3),
                                                likeBuilder: (isLike) {
                                                  return isLike == true
                                                      ? Image.asset(
                                                          'assets/images/common/red_heart.webp')
                                                      : Icon(
                                                          Icons
                                                              .favorite_border_outlined,
                                                          size: 20,
                                                          color: WcaoTheme
                                                              .secondary,
                                                        );
                                                },
                                                bubblesColor:
                                                    const BubblesColor(
                                                  dotPrimaryColor:
                                                      ColorRes.color_3,
                                                  dotSecondaryColor:
                                                      ColorRes.color_3,
                                                  dotThirdColor:
                                                      ColorRes.color_3,
                                                  dotLastColor:
                                                      ColorRes.color_3,
                                                )),
                                            Text(
                                              e.likeCount.toString(),
                                              style: TextStyle(
                                                  fontSize: 12,
                                                  color: Colors.grey),
                                            ),
                                          ],
                                        ),
                                      ],
                                    ),
                                  ));
                                }))),
                  ])),
              Positioned(
                  bottom: 0,
                  left: 0,
                  child: Container(
                      width: MediaQuery.of(context).size.width,
                      height:
                          isShowkeyborad || _commentEditController.text != ""
                              ? 100
                              : 40,
                      decoration: BoxDecoration(
                        color: Colors.white,
                      ),
                      child: Column(children: [
                        Divider(
                          height: 1,
                          color: Colors.black12,
                        ),
                        Expanded(
                            child: Container(
                          alignment: Alignment.center,
                          padding: EdgeInsets.symmetric(horizontal: 10),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Expanded(
                                  flex: 1,
                                  child: Container(
                                    alignment: Alignment.topLeft,
                                    padding:
                                        EdgeInsets.only(left: 10, right: 10),
                                    margin: EdgeInsets.only(
                                        left: 10, right: 6, top: 4, bottom: 4),
                                    decoration: BoxDecoration(
                                        borderRadius: BorderRadius.circular(20),
                                        color: Colors.grey[100]),
                                    child: TextField(
                                      controller: _commentEditController,
                                      cursorColor: Colors.redAccent,
                                      focusNode: _focusNode,
                                      keyboardType: TextInputType.multiline,
                                      maxLines: isShowkeyborad ||
                                              _commentEditController.text != ""
                                          ? 20
                                          : 1,
                                      minLines: 1,
                                      style: TextStyle(
                                          color: Colors.black, fontSize: 11),
                                      decoration: InputDecoration(
                                          // border: OutlineInputBorder(),
                                          border: InputBorder.none,
                                          hintText: parentComment != null
                                              ? '回复' +
                                                  parentComment.userName +
                                                  '：'
                                              : '写评论...',
                                          hintStyle: TextStyle(
                                              color: Colors.grey[600])),
                                    ),
                                  )),
                              InkWell(
                                child: Container(
                                  margin: EdgeInsets.only(left: 10),
                                  alignment: Alignment.center,
                                  child: Image.asset(
                                    'assets/images/icons/publish_at.png',
                                    width: 20,
                                    height: 20,
                                  ),
                                ),
                                onTap: showBottomFriendList,
                              ),
                              Container(
                                  height: 30,
                                  width: 60,
                                  margin: EdgeInsets.only(left: 10, right: 10),
                                  alignment: Alignment.center,
                                  child: ElevatedButton(
                                      style: ButtonStyle(
                                          shape: MaterialStateProperty.all(
                                              RoundedRectangleBorder(
                                                  borderRadius:
                                                      BorderRadius.circular(
                                                          20))),
                                          backgroundColor:
                                              MaterialStateProperty.all(
                                            Colors.redAccent,
                                          )),
                                      onPressed: disabledPublish
                                          ? publishComment
                                          : null,
                                      child: const Center(
                                        child: Text(
                                          '发送',
                                          style: TextStyle(
                                              color: Colors.white,
                                              fontSize: 12,
                                              fontWeight: FontWeight.w500),
                                        ),
                                      ))),
                            ],
                          ),
                        ))
                      ])))
            ])));
  }

  //展示好友
  void showBottomFriendList() {
    showModalBottomSheet(
        backgroundColor: Colors.white,
        context: context,
        isScrollControlled: true, //可滚动 解除showModalBottomSheet最大显示屏幕一半的限制
        shape: RoundedRectangleBorder(
          borderRadius: const BorderRadius.only(
            topLeft: Radius.circular(10),
            topRight: Radius.circular(10),
          ),
        ),
        builder: (context) {
          return Container(
              constraints: BoxConstraints(
                  minHeight: MediaQuery.of(context).size.height -
                      kToolbarHeight, //设置最小高度（必要）
                  maxHeight: MediaQuery.of(context).size.height
                  // -
                  //     kToolbarHeight, //设置最大高度（必要）
                  ),
              child: FriendListSelectPublishIndexPage());
        });
  }

  Future<bool> onTapLikeButton(bool isLiked, int index) async {
    if (index != -1) {
      _commentListModel[index].hasLiked = isLiked;
      if (isLiked) {
        _commentListModel[index].likeCount++;
      } else {
        _commentListModel[index].likeCount--;
      }
      Map<String, dynamic> data = {
        "targetId": _commentListModel[index].id,
        "targetType": 'COMMENT',
      };
      if (isLiked) {
        await OperationServiece.like(data);
      } else {
        await OperationServiece.cancelLike(data);
      }
      setState(() {
        _commentListModel = _commentListModel;
      });
    } else {
      _commentDetail.hasLiked = isLiked;
      if (isLiked) {
        _commentDetail.likeCount++;
      } else {
        _commentDetail.likeCount--;
      }
      Map<String, dynamic> data = {
        "targetId": _commentDetail.id,
        "targetType": 'COMMENT',
      };
      if (isLiked) {
        await OperationServiece.like(data);
      } else {
        await OperationServiece.cancelLike(data);
      }
      setState(() {
        _commentDetail = _commentDetail;
      });
    }
    return isLiked;
  }

  publishComment() async {
    EasyLoading.show(status: '发送中...');
    try {
      setState(() {
        disabledPublish = false;
      });
      Map<String, dynamic> data = {
        "momentId": widget.momentId,
        "content": _commentEditController.text,
        "parentId": widget.commentId,
        "replyToId": parentComment != null ? parentComment.id : 0,
      };
      Map<String, dynamic> result = await CommentService.publishComment(data);
      CommentDetailModel commentDetail;
      Map<String, dynamic> param = {
        "commentId": result['body'],
      };
      Map<String, dynamic> commentResult =
          await CommentService.getCommentDetail(param);
      commentDetail = CommentDetailModel.fromJson(commentResult['body']);
      if (parentComment != null) {
        for (int i = 0; i < _commentListModel.length; i++) {
          if (_commentListModel[i].id == parentComment.id) {
            commentDetail.replyToComment = _commentListModel[i];
          }
        }
      }
      setState(() {
        _commentListModel.insert(0, commentDetail);
        parentComment = null;
        _commentEditController.text = "";
        disabledPublish = true;
        _focusNode.unfocus();
      });
      ToastUtils.showToast("发送成功");
      EasyLoading.dismiss(animation: true);
    } catch (e) {
      setState(() {
        disabledPublish = true;
      });
      EasyLoading.showError(e['retdesc'] != null ? e['retdesc'] : '发送失败');
      EasyLoading.dismiss(animation: true);
    }
  }

  @override
  bool get wantKeepAlive => true;
}
